package com.briup.gsauestore.service.impl;

import com.briup.gsauestore.bean.*;
import com.briup.gsauestore.dao.IOrderDao;
import com.briup.gsauestore.dao.IOrderItemDao;
import com.briup.gsauestore.dao.IShopCarDao;
import com.briup.gsauestore.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author adam
 * @date 2022/1/12
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderDao orderDao;
    @Autowired
    private IShopCarDao shopCarDao;
    @Autowired
    private IOrderItemDao itemDao;

    @Override
    public List<Order> findUserAllOrders(Long userId) {
        List<Order> list = orderDao.findByUserId(userId);
        return list;
    }

    @Override
    @Transactional
    public Order saveOrder(Long[] shopCarIds, User user, Long addressId) {
        ShippingAddress address = new ShippingAddress();
        address.setId(addressId);
        Order order = new Order(user, address);
//        设置订单状态 未支付
        order.setStatus(1);
        ArrayList<OrderItem> list = new ArrayList<>();
        for (Long shopCarId : shopCarIds) {
            ShopCar car = shopCarDao.findById(shopCarId).get();
//            构建订单项
            OrderItem item = new OrderItem(car);
            list.add(item);
        }
//        为订单设置订单项
        order.setOrderItems(list);

//        保存订单
        orderDao.save(order);
//        保存订单项
        for (OrderItem item : list) {
            item.setOrder(order);
            itemDao.save(item);
        }

//        删除购物车数据
        for (Long id : shopCarIds) {
            shopCarDao.deleteById(id);
        }
        return order;

    }

    @Override
    public Order paySuccess(String orderId) {
//        修改订单状态为已支付待发货 同步到数据库
        orderDao.updateStatusById(2, orderId);
//        通过id查order的信息
        Order order = orderDao.findById(orderId).get();
        return order;
    }

    @Override
    public Order findById(String orderId) {

        return null;
    }
}
